from flask import current_app, jsonify, render_template, abort, session, g, request

from . import news_blue
from ... import db
from ...models import News, User, Comment, CommentLike
from ...utils.commons import user_login_data
from ...utils.response_code import RET

'''
新闻详情展示(新闻)
请求路径: /news/<int:news_id>
请求方式: GET
请求参数:news_id
返回值: detail.html页面, 用户,新闻data字典数据

'''
@news_blue.route("/<int:news_id>")
@user_login_data
def get_news_detail(news_id):
    # user_id=session.get("user_id")
    # user=None
    # if user_id:
    #     try:
    #         user=User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)

    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻详情获取异常")

    if not news:
        abort(404)
    # 查询热榜
    try:
        news_click = News.query.order_by(News.clicks.desc()).limit(6).all()
    except Exception as e:
        current_app.logger.error(e)
        # print(e)
    news_list = []
    for item in news_click:
        news_list.append(item.to_dict())
    #     查询用户是否收藏过新闻
    is_collected = False
    if g.user:
        if news in g.user.collection_news:
            is_collected = True
    try:
        comments = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询评论列表失败")
    # 获取用户评论点赞列表
    try:
        commentLikes = []
        if g.user:
            commentLikes = CommentLike.query.filter(g.user.id == CommentLike.user_id).all()
        mylike_comment_list = []
        for commentLike in commentLikes:
            mylike_comment_list.append(commentLike.comment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DATAERR, errmsg="查询点赞列表失败")
    # 评论数据
    comment_list = []
    for comment in comments:
        comment_dict = comment.to_dict()
        comment_dict["is_like"] = False
        if g.user and comment.id in mylike_comment_list:
            comment_dict["is_like"] = True
        comment_list.append(comment_dict)
    # 查询用户是否关注了其他用户
    is_followed=False
    #用户以登录且文章有作者
    #用户在作者的粉丝列表中就是关注了
    if g.user and news.user :
        if g.user in news.user.followers:
            is_followed=True
    data = {
        "news_info": news.to_dict() if news else "",
        "user_info": g.user.to_dict() if g.user else "",
        "news_list": news_list,
        "is_collected": is_collected,
        "comments": comment_list,
        "is_followed": is_followed
    }
    print("评论数据", comment_list)

    return render_template("news/detail.html", data=data)


'''
请求路径: /news/news_collect
请求方式: POST
请求参数:news_id,action, g.user
返回值: errno,errmsg 
'''


# 收藏功能
@news_blue.route("/news_collect", methods=["POST"])
@user_login_data
def news_collect():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    news_id = request.json.get("news_id")
    action = request.json.get("action")  # 操作类型
    print(news_id, action)
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    # 取出新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
    if not news:
        return jsonify(errno=RET.DBERR, errmsg="新闻对象不存在")
    if not action in ['collect', 'cancel_collect']:
        return jsonify(errno=RET.DBERR, errmsg="操作类型不存在")
    # 操作
    if action == 'collect':
        # 已收藏取消收藏
        if not news in g.user.collection_news:
            g.user.collection_news.append(news)
    else:
        if news in g.user.collection_news:
            g.user.collection_news.remove(news)
    return jsonify(errno=RET.OK, errmsg="操作成功")


'''
请求路径: /news/news_comment
请求方式: POST
请求参数:news_id,comment,parent_id
返回值: errno,errmsg,评论字典
'''


# 评论功能实现
@news_blue.route("/news_comment", methods=["POST"])
@user_login_data
def news_comment():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    news_id = request.json.get("news_id")
    comment_msg = request.json.get("comment")
    parent_id = request.json.get("parent_id")
    print(parent_id, comment_msg, news_id)
    if not all([news_id, comment_msg]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="新闻查询异常")
    if not news:
        return jsonify(errno=RET.DBERR, errmsg="新闻不存在")
    comment = Comment()
    comment.news_id = news_id
    comment.user_id = g.user.id
    comment.content = comment_msg
    if parent_id:
        comment.parent_id = parent_id
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="评论失败")
    print("评论成功", comment.user_id)
    return jsonify(errno=RET.OK, errmsg="评论成功", data=comment.to_dict())


'''
15.评论点赞
请求路径: /news/comment_like
请求方式: POST
请求参数:news_id,comment_id,action,g.user
返回值: errno,errmsg
'''
@news_blue.route("/comment_like", methods=["POST"])
@user_login_data
def comment_like():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")
    commment_id = request.json.get("comment_id")
    action = request.json.get("action")
    if not all([action, commment_id]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    if not action in ["add", "remove"]:
        return jsonify(errno=RET.NODATA, errmsg="操作类型有误")
    try:
        comment = Comment.query.get(commment_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="评论查询失败")
    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论不存在")
    # print(action,commment_id)
    if action == "add":
        # 判断是否给评论点过赞
        my_comment_like = CommentLike.query.filter(CommentLike.user_id==g.user.id,CommentLike.comment_id==comment.id).first()
        # 没有点过赞 添加点赞
        if not my_comment_like:
            try:
                commentLike = CommentLike()
                commentLike.comment_id = comment.id
                commentLike.user_id = g.user.id
                # print(commentLike)
                db.session.add(commentLike)
                comment.like_count += 1
                db.session.commit()
            except Exception as e:
                current_app.logger.error(e)
                return jsonify(errno=RET.DBERR, errmsg="点赞失败")

    else:
        # 判断是否给评论点过赞
        my_comment_like = CommentLike.query.filter(CommentLike.user_id == g.user.id,
                                                   CommentLike.comment_id == comment.id).first()
        # try:
            # 有点过赞 移除点赞
        if my_comment_like:
                db.session.delete(my_comment_like)
                if comment.like_count > 0:
                    comment.like_count -= 1
                db.session.commit()
        # except Exception as e:
        #     current_app.logger.error(e)
        #     return jsonify(errno=RET.DBERR, errmsg="删除点赞失败")
    return  jsonify(errno=RET.OK ,errmsg="点赞成功")
'''
关注与取消关注
请求路径: /news/followed_user
请求方式: POST
请求参数:user_id,action
返回值: errno, errmsg
'''
@news_blue.route("/followed_user",methods=["POST"])
@user_login_data
def followed_user():
    if not g.user:
        return jsonify(errno=RET.SESSIONERR,errmsg="用户未登陆")
    author_id=request.json.get("user_id")
    action=request.json.get("action")

    if not all([author_id,action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")
    try:
       author=User.query.get(author_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR, errmsg="查询作者失败")
    # 自己不能关注自己
    # if g.user.id==author.id:
    #     return jsonify(errno=RET.DATAERR, errmsg="自己不能关注自己")

    if not author:
        return jsonify(errno=RET.NODATA,errmsg="作者不存在")
    if action not in ["follow","unfollow"]:
        return jsonify(errno=RET.DBERR,errmsg="操作类型错误")
    # 关注与取消关注操作
    if action=="follow":
        # 用户是否在作者的粉丝列表中 不在就关注
        if g.user not in author.followers:
            author.followers.append(g.user)
    else:
        if g.user in author.followers:
            author.followers.remove(g.user)
    return jsonify(errno=RET.OK,errmsg="关注成功")
